<template>
  <div class="authority">
    <warning-bar title="注：右上角头像下拉可切换角色" />
    <div class="gva-table-box">


      <div class="gva-search-box">
        <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">


<!--          <el-form-item label="角色名称" prop="authorityName">-->
<!--            <template #label>-->
<!--    <span>-->
<!--      角色名称-->
<!--      <el-tooltip content="要搜索角色的名字">-->
<!--        <el-icon><QuestionFilled /></el-icon>-->
<!--      </el-tooltip>-->
<!--    </span>-->
<!--            </template>-->

            <el-form-item label="角色名称">
              <el-input
                  v-model="searchInfo.authorityName"
                  placeholder="角色名称"
              />

          </el-form-item>



          <el-form-item label="创建日期" prop="createdAt">
            <template #label>
    <span>
      创建日期
      <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
        <el-icon><QuestionFilled /></el-icon>
      </el-tooltip>
    </span>
            </template>
            <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
            —
            <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
          </el-form-item>
          <el-form-item>


            <!--            <el-button type="primary" icon="search" @click="getAuthorityList">查询</el-button>-->
            <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button icon="refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="gva-btn-list">
        <el-button
            type="primary"
            icon="plus"
            @click="addAuthority(0)"
        >新增角色</el-button>
        <el-icon
            class="cursor-pointer"
            @click="toDoc('https://www.bilibili.com/video/BV1kv4y1g7nT?p=8&vd_source=f2640257c21e3b547a790461ed94875e')"
        ><VideoCameraFilled /></el-icon>
      </div>
      <el-table
          :data="tableData"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          row-key="authorityId"
          style="width: 100%"
      >

        <el-table-column
            label="角色ID"
            min-width="180"
            prop="authorityId"
        />
        <el-table-column
            align="left"
            label="角色名称"
            min-width="180"
            prop="authorityName"
        />

        <el-table-column
            align="left"
            label="角色描述"
            min-width="180"
            prop="authorityDesc"
        />

        <el-table-column
            align="left"
            label="启用"
            min-width="150"
        >
          <template #default="scope">
            <el-switch
                v-model="scope.row.authorityState"
                inline-prompt
                :active-value="1"
                :inactive-value="2"
                @change="()=>{switchEnable(scope.row)}"
            />
          </template>
        </el-table-column>

        <el-table-column
            align="left"
            label="创建人"
            min-width="180"
            prop="authorityByCreate"
        />

        <el-table-column
            align="left"
            label="创建时间"
            min-width="180"
            prop="CreatedAt"
        />


        <el-table-column
            align="left"
            label="操作"
            width="460"
        >
          <template #default="scope">
            <el-button
                icon="setting"

                type="primary"
                link
                @click="opdendrawer(scope.row)"
            >设置权限</el-button>
            <el-button
                icon="plus"

                type="primary"
                link
                @click="addAuthority(scope.row.authorityId)"
            >新增子角色</el-button>
            <el-button
                icon="copy-document"

                type="primary"
                link
                @click="copyAuthorityFunc(scope.row)"
            >拷贝</el-button>
            <el-button
                icon="edit"

                type="primary"
                link
                @click="editAuthority(scope.row)"
            >编辑</el-button>
            <el-button
                icon="delete"

                type="primary"
                link
                @click="deleteAuth(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>


    <div class="gva-pagination">
      <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
      />
    </div>



    <!-- 新增角色弹窗 -->
    <el-dialog
        v-model="dialogFormVisible"
        :title="dialogTitle"
    >
      <el-form
          ref="authorityForm"
          :model="form"
          :rules="rules"
          label-width="80px"
      >
        <el-form-item
            label="父级角色"
            prop="parentId"
        >

          <el-cascader
              v-model="form.parentId"
              style="width:100%"
              :disabled="dialogType==='add'"
              :options="AuthorityOption"
              :props="{ checkStrictly: true,label:'authorityName',value:'authorityId',disabled:'disabled',emitPath:false}"
              :show-all-levels="false"
              filterable
          />


        </el-form-item>
<!--        <el-form-item-->
<!--            label="角色ID"-->
<!--            prop="authorityId"-->
<!--        >-->
<!--          <el-input-->
<!--              v-model="form.authorityId"-->
<!--              :disabled="dialogType==='edit'"-->
<!--              autocomplete="off"-->
<!--              maxlength="15"-->
<!--          />-->
<!--        </el-form-item>-->


        <el-form-item
            label="角色姓名"
            prop="authorityName"
        >
          <el-input
              v-model="form.authorityName"
              autocomplete="off"
          />
        </el-form-item>

        <el-form-item
            label="创建人"
            prop="creater"

        >

          <el-input
              v-model="creater"
              autocomplete="off"
              maxlength="15"
              :disabled="true"
          />


        </el-form-item>

        <el-form-item
            label="角色描述"
            prop="authorityDesc"
        >
          <el-input
              v-model="form.authorityDesc"
              :disabled="dialogType==='edit'"
              autocomplete="off"
              maxlength="15"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
              type="primary"
              @click="enterDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-drawer
        v-if="drawer"
        v-model="drawer"
        custom-class="auth-drawer"
        :with-header="false"
        size="40%"
        title="角色配置"
    >
      <el-tabs
          :before-leave="autoEnter"
          type="border-card"
      >
        <el-tab-pane label="角色菜单">
          <Menus
              ref="menus"
              :row="activeRow"
              @changeRow="changeRow"
          />
        </el-tab-pane>
        <el-tab-pane label="角色api">
          <Apis
              ref="apis"
              :row="activeRow"
              @changeRow="changeRow"
          />
        </el-tab-pane>
        <el-tab-pane label="资源权限">
          <Datas
              ref="datas"
              :authority="tableData"
              :row="activeRow"
              @changeRow="changeRow"
          />
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </div>
</template>

<script setup>
import {
  getAuthorityList,
  deleteAuthority,
  createAuthority,
  updateAuthority,
  copyAuthority
} from '@/api/authority'

import Menus from '@/view/superAdmin/authority/components/menus.vue'
import Apis from '@/view/superAdmin/authority/components/apis.vue'
import Datas from '@/view/superAdmin/authority/components/datas.vue'
import WarningBar from '@/components/warningBar/warningBar.vue'

import {nextTick, reactive, ref} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { toDoc } from '@/utils/doc'
import { VideoCameraFilled } from '@element-plus/icons-vue'
import {getUserInfo, setUserInfo} from "@/api/user";
import {useUserStore} from "@/pinia/modules/user";

//向后端传输数据

const publishTime = async ()=>{

  const res = await axios.post('/api/searchtime')

  console.log(res);

}

defineOptions({
  name: 'Authority'
})


const mustUint = (rule, value, callback) => {
  if (!/^[0-9]*[1-9][0-9]*$/.test(value)) {
    return callback(new Error('请输入正整数'))
  }
  return callback()
}

const AuthorityOption = ref([
  {
    authorityId: 0,
    authorityName: '根角色'
  }
])
const drawer = ref(false)
const dialogType = ref('add')
const activeRow = ref({})

const dialogTitle = ref('新增角色')
const dialogFormVisible = ref(false)
const apiDialogFlag = ref(false)
const copyForm = ref({})

const form = ref({
  authorityName: '',
  authorityByCreate: '',
  authorityDesc: '',

  parentId: 0
})


const rules = ref({
  authorityId: [
    { required: true, message: '请输入角色ID', trigger: 'blur' },
    { validator: mustUint, trigger: 'blur', message: '必须为正整数' }
  ],
  authorityName: [
    { required: true, message: '请输入角色名', trigger: 'blur' }
  ],
  parentId: [
    { required: true, message: '请选择父角色', trigger: 'blur' },
  ]
})
// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}
const elSearchFormRef = ref()

const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10

    getTableData()
  })
}

const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})


// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {

  const table = await getAuthorityList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })

  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

const userStore = useUserStore()
const creater = userStore.userInfo.nickName

getTableData()

const changeRow = (key, value) => {
  activeRow.value[key] = value
}
const menus = ref(null)
const apis = ref(null)
const datas = ref(null)
const autoEnter = (activeName, oldActiveName) => {
  const paneArr = [menus, apis, datas]
  if (oldActiveName) {
    if (paneArr[oldActiveName].value.needConfirm) {
      paneArr[oldActiveName].value.enterAndNext()
      paneArr[oldActiveName].value.needConfirm = false
    }
  }
}
// 拷贝角色
const copyAuthorityFunc = (row) => {
  setOptions()
  dialogTitle.value = '拷贝角色'
  dialogType.value = 'copy'
  for (const k in form.value) {
    form.value[k] = row[k]
  }
  copyForm.value = row
  dialogFormVisible.value = true
}
const opdendrawer = (row) => {
  drawer.value = true
  activeRow.value = row
}
// 删除角色
const deleteAuth = (row) => {
  ElMessageBox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(async() => {
        const res = await deleteAuthority({ authorityId: row.authorityId })
        if (res.code === 0) {
          ElMessage({
            type: 'success',
            message: '删除成功!'
          })
          if (tableData.value.length === 1 && page.value > 1) {
            page.value--
          }
          getTableData()
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除'
        })
      })
}
// 初始化表单
const authorityForm = ref(null)
const initForm = () => {
  if (authorityForm.value) {
    authorityForm.value.resetFields()
  }
  form.value = {
    authorityName: '',
    parentId: 0
  }
}
const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
        if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
          callback(new Error('请填写结束日期'))
        } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
          callback(new Error('请填写开始日期'))
        } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
          callback(new Error('开始日期应当早于结束日期'))
        } else {
          callback()
        }
      }, trigger: 'change' }
  ],
})

const switchEnable = async(row) => {
  var info = JSON.parse(JSON.stringify(row))
  console.log(info)
  await nextTick()
  const res = await updateAuthority(info)
  if (res.code === 0) {
    ElMessage({ type: 'success', message: `${req.enable === 2 ? '禁用' : '启用'}成功` })
    await getTableData()
  }
}


// 关闭窗口
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
  apiDialogFlag.value = false
}
// 确定弹窗

const enterDialog = () => {

  form.value.authorityByCreate=creater
  authorityForm.value.validate(async valid => {
    if (valid) {
      form.value.authorityId = Number(form.value.authorityId)
      switch (dialogType.value) {
        case 'add':
        {
          const res = await createAuthority(form.value)
          if (res.code === 0) {
            ElMessage({
              type: 'success',
              message: '添加成功!'
            })
            getTableData()
            closeDialog()
          }
        }
          break
        case 'edit':
        {
          const res = await updateAuthority(form.value)
          if (res.code === 0) {
            ElMessage({
              type: 'success',
              message: '添加成功!'
            })
            getTableData()
            closeDialog()
          }
        }
          break
        case 'copy': {
          const data = {
            authority: {
              authorityId: 0,
              authorityName: '',
              datauthorityId: [],
              parentId: 0
            },
            oldAuthorityId: 0
          }
          data.authority.authorityId = form.value.authorityId
          data.authority.authorityName = form.value.authorityName
          data.authority.parentId = form.value.parentId
          data.authority.dataAuthorityId = copyForm.value.dataAuthorityId
          data.oldAuthorityId = copyForm.value.authorityId
          const res = await copyAuthority(data)
          if (res.code === 0) {
            ElMessage({
              type: 'success',
              message: '复制成功！'
            })
            getTableData()
          }
        }
      }

      initForm()
      dialogFormVisible.value = false
    }
  })
}
const setOptions = () => {
  AuthorityOption.value = [
    {
      authorityId: 0,
      authorityName: '根角色'
    }
  ]
  setAuthorityOptions(tableData.value, AuthorityOption.value, false)
}
const setAuthorityOptions = (AuthorityData, optionsData, disabled) => {
  form.value.authorityId = String(form.value.authorityId)
  AuthorityData &&
  AuthorityData.forEach(item => {
    if (item.children && item.children.length) {
      const option = {
        authorityId: item.authorityId,
        authorityName: item.authorityName,
        disabled: disabled || item.authorityId === form.value.authorityId,
        children: []
      }
      setAuthorityOptions(
          item.children,
          option.children,
          disabled || item.authorityId === form.value.authorityId
      )
      optionsData.push(option)
    } else {
      const option = {
        authorityId: item.authorityId,
        authorityName: item.authorityName,
        disabled: disabled || item.authorityId === form.value.authorityId
      }
      optionsData.push(option)
    }
  })
}
// 增加角色
const addAuthority = (parentId) => {
  initForm()
  dialogTitle.value = '新增角色'
  dialogType.value = 'add'
  form.value.parentId = parentId

  setOptions()
  dialogFormVisible.value = true
}
// 编辑角色
const editAuthority = (row) => {
  setOptions()
  dialogTitle.value = '编辑角色'
  dialogType.value = 'edit'
  for (const key in form.value) {
    form.value[key] = row[key]
  }
  setOptions()
  dialogFormVisible.value = true
}

</script>

<style lang="scss">
.authority {
  .el-input-number {
    margin-left: 15px;
    span {
      display: none;
    }
  }
}
.tree-content{
  margin-top: 10px;
  height: calc(100vh - 158px);
  overflow: auto;
}

</style>